package com.gycode.vpush.aop;


import com.gycode.vpush.dto.base.ResultDTO;
import com.gycode.vpush.enums.ResultEnum;
import com.gycode.vpush.utils.ResultDTOUtil;
import com.gycode.vpush.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;


/**
 * @author lgy
 * Date: Created in 2021/6/22 11:02
 * Utils: Intellij Idea
 * Description: 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandling {

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = CustomException.class)
    public ResultDTO processException(CustomException e) {
        // return ResultDTOUtil.error(Objects.requireNonNull(ResultEnum.getByCode(e.getCode())));
        return ResultDTOUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * 拦截表单参数校验
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({BindException.class})
    public ResultDTO bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ResultDTOUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    /**
     * 拦截JSON参数校验
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultDTO bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ResultDTOUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }


    /**
     * 通用异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ResultDTO exception(Exception e) {
        e.printStackTrace();
        return ResultDTOUtil.error(ResultEnum.UNKNOWN_EXCEPTION);
    }
}
